package com.eco.interceptor;

import com.alibaba.fastjson.JSON;
import com.eco.annotation.AuthToken;
import com.eco.entity.User;
import com.eco.service.UserService;
import com.github.benmanes.caffeine.cache.Cache;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    Cache<String, Object> caffeineCache;

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        if (!(handler instanceof HandlerMethod))
            return true;
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        if (method.getAnnotation(AuthToken.class) == null && handlerMethod.getBeanType().getAnnotation(AuthToken.class) == null)
            return true;
        String token = request.getHeader("Authorization");
        Map<String, Object> result = new HashMap<>(4);
        if (StringUtils.isBlank(token)) {
            result.put("code", Integer.valueOf(HttpStatus.UNAUTHORIZED.value()));
            result.put("msg", "没有权限！token为空，请先登录");
                    result.put("status", Boolean.valueOf(false));
            PrintWriter writer = response.getWriter();
            try {
                writer.append(JSON.toJSONString(result));
                if (writer != null)
                {
                    writer.close();
                }
            } catch (Throwable throwable) {
                if (writer != null)
                {
                    try {
                        writer.close();
                    } catch (Throwable throwable1) {
                        throwable.addSuppressed(throwable1);
                    }
                }
                throw throwable;
            }
            return false;
        }
        String userId = null;
        try {
            userId = (String)this.caffeineCache.getIfPresent(token);
        } catch (Exception e) {
            log.error("Cache已经断开闲置的连接");
        }
        if (StringUtils.isNotEmpty(userId)) {
            AuthToken annotation = method.<AuthToken>getAnnotation(AuthToken.class);
            String value = annotation.value();
            if (StringUtils.isEmpty(value)) {
                this.caffeineCache.put(token, userId);
                return true;
            }
            User userRole = this.userService.findByUserIdAndUsername(Integer.valueOf(userId), value);
            if (userRole == null) {
                try {
                    PrintWriter writer = response.getWriter();
                    try {
                        result.put("code", Integer.valueOf(HttpStatus.FORBIDDEN.value()));
                        result.put("msg", "失败，没有该操作权限!");
                                result.put("status", Boolean.valueOf(false));
                        writer.append(JSON.toJSONString(result));
                        boolean bool = false;
                        if (writer != null)
                        {
                            writer.close();
                        }
                        return bool;
                    } catch (Throwable throwable) {
                        if (writer != null){
                            try {
                                writer.close();
                            } catch (Throwable throwable1) {
                                throwable.addSuppressed(throwable1);
                            }
                        }
                        throw throwable;
                    }
                } catch (Exception e) {
                    log.error(e.toString());
                }
            } else {
                this.caffeineCache.put(token, userId);
                return true;
            }
        } else {
            try {
                PrintWriter writer = response.getWriter();
                try {
                    result.put("code", Integer.valueOf(HttpStatus.UNAUTHORIZED.value()));
                    result.put("msg", "过期失效，请重新登录");
                            result.put("status", Boolean.valueOf(false));
                    writer.append(JSON.toJSONString(result));
                    boolean bool = false;
                    if (writer != null)
                    {
                        writer.close();
                    }
                    return bool;
                } catch (Throwable throwable) {
                    if (writer != null)
                    {
                        try {
                            writer.close();
                        } catch (Throwable throwable1) {
                            throwable.addSuppressed(throwable1);
                        }
                    }
                    throw throwable;
                }
            } catch (Exception e) {
                log.error(e.toString());
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}
}
